import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import '../services/constants.dart';
import '../services/token_manager.dart';

class OrderDetailPage extends StatefulWidget {
  final Map<String, dynamic> order;
  const OrderDetailPage({super.key, required this.order});

  @override
  State<OrderDetailPage> createState() => _OrderDetailPageState();
}

class _OrderDetailPageState extends State<OrderDetailPage> {
  Map<String, dynamic>? order;
  bool loading = true;
  String userEmail = '';

  @override
  void initState() {
    super.initState();
    order = Map<String, dynamic>.from(widget.order);
    _loadDetail();
  }

  Map<String, String> _headers() => {
        'Content-Type': 'application/json',
        if (userEmail.isNotEmpty) 'email': userEmail,
      };

  Future<void> _loadDetail() async {
    setState(() => loading = true);
    final info = await TokenManager.instance.getUserInfo();
    userEmail = info['email'] ?? '';
    try {
      final dynamic oid = order != null ? order!['id'] : null;
      final int id = oid is int ? oid : int.tryParse((oid ?? '').toString()) ?? 0;
      if (id == 0) {
        setState(() => loading = false);
        return;
      }
      final url = Uri.parse('${Constants.serverUrl}order/detail?orderId=$id');
      final res = await http.get(url, headers: _headers());
      if (res.statusCode == 200) {
        final data = jsonDecode(res.body);
        if (data['code'] == 0 && data['data'] is Map) {
          order = Map<String, dynamic>.from(data['data']);
        }
      }
    } catch (_) {}
    if (mounted) setState(() => loading = false);
  }

  String _statusText(int status) {
    switch (status) {
      case 10:
        return '待发货';
      case 20:
        return '待收货';
      case 30:
        return '已完成';
      default:
        return '未知状态';
    }
  }

  @override
  Widget build(BuildContext context) {
    final o = order ?? {};
    final List<String> goodsImages = (() {
      final raw = o['goodsImages'];
      if (raw is String) {
        return raw.split(',').where((e) => e.trim().isNotEmpty).toList();
      }
      if (raw is List) return raw.cast<String>();
      return <String>[];
    })();

    return Scaffold(
      appBar: AppBar(title: const Text('订单详情')),
      body: loading
          ? const Center(child: CircularProgressIndicator())
          : RefreshIndicator(
              onRefresh: _loadDetail,
              child: ListView(
                children: [
                  Container(
                    color: Colors.white,
                    padding: const EdgeInsets.all(15),
                    child: Row(
                      children: [
                        Icon(Icons.local_shipping_outlined, size: 24, color: Colors.orange[700]),
                        const SizedBox(width: 10),
                        Text(
                          _statusText((o['status'] ?? 0) as int),
                          style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
                        ),
                      ],
                    ),
                  ),
                  const SizedBox(height: 10),
                  Container(
                    color: Colors.white,
                    padding: const EdgeInsets.all(15),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(children: [
                          Icon(Icons.location_on, size: 20, color: Colors.red[700]),
                          const SizedBox(width: 6),
                          const Text('收货地址', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                        ]),
                        const SizedBox(height: 10),
                        Text('${o['addressName'] ?? ''}  ${o['addressPhone'] ?? ''}', style: const TextStyle(fontSize: 15)),
                        const SizedBox(height: 6),
                        Text((o['addressDetail'] ?? '').toString(), style: TextStyle(fontSize: 14, color: Colors.grey[700])),
                      ],
                    ),
                  ),
                  const SizedBox(height: 10),
                  Container(
                    color: Colors.white,
                    padding: const EdgeInsets.all(15),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text('商品信息', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                        const SizedBox(height: 15),
                        Row(children: [
                          Container(
                            width: 80,
                            height: 80,
                            decoration: BoxDecoration(color: Colors.grey[300], borderRadius: BorderRadius.circular(8)),
                            clipBehavior: Clip.antiAlias,
                            child: goodsImages.isNotEmpty
                                ? Image.network(goodsImages.first, fit: BoxFit.cover)
                                : Icon(Icons.image_outlined, size: 40, color: Colors.grey[400]),
                          ),
                          const SizedBox(width: 12),
                          Expanded(
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text((o['goodsName'] ?? '').toString(), style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w500), maxLines: 2, overflow: TextOverflow.ellipsis),
                                const SizedBox(height: 8),
                                Text('¥${o['goodsPrice'] ?? ''}', style: TextStyle(color: Colors.red[700], fontSize: 16, fontWeight: FontWeight.bold)),
                              ],
                            ),
                          ),
                        ]),
                      ],
                    ),
                  ),
                  const SizedBox(height: 10),
                  Container(
                    color: Colors.white,
                    padding: const EdgeInsets.all(15),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        const Text('订单信息', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
                        const SizedBox(height: 15),
                        _row('订单编号', (o['orderNo'] ?? '').toString()),
                        const SizedBox(height: 10),
                        _row(
                          '下单时间',
                          (() {
                            final t = o['createTime'];
                            final s = t is int ? t : int.tryParse((t ?? '').toString()) ?? 0;
                            if (s == 0) return '';
                            return DateTime.fromMillisecondsSinceEpoch(s * 1000).toLocal().toString().substring(0, 19);
                          })(),
                        ),
                        const SizedBox(height: 10),
                        _row('订单金额', '¥${o['goodsPrice'] ?? ''}'),
                      ],
                    ),
                  ),
                  const SizedBox(height: 80),
                ],
              ),
            ),
    );
  }

  Widget _row(String label, String value) {
    return Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        SizedBox(width: 80, child: Text(label, style: TextStyle(fontSize: 14, color: Colors.grey[600]))),
        Expanded(child: Text(value, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w500))),
      ],
    );
  }
}


